<template>
  <div class="app-container">
    <el-card class="box-card">


      <div class="filter-container">
        <el-input placeholder="模版名称" class="filter-item search-item"
                  v-model="queryParams.model.name"/>

        <el-button @click="handleQuery" class="filter-item" plain type="primary">{{ $t('table.search') }}</el-button>
        <el-button @click="reset" class="filter-item" plain type="warning">{{ $t('table.reset') }}</el-button>
        <el-button @click="handleCreate" class="filter-item" plain type="danger" v-has-permission="['authority:application:add']">
          {{ $t("table.add") }}
        </el-button>

      </div>
      <el-table
        :data="tableData.records"
        :key="tableKey"
        @cell-click="cellClick"
        @filter-change="filterChange"
        @selection-change="onSelectChange"
        @sort-change="sortChange"
        border fit row-key="id"
        ref="table"
        style="width: 100%;"
        v-loading="loading"
      >
        <el-table-column label="名称" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="120px" prop="name">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建者" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="60px" prop="createName">
          <template slot-scope="scope">
            <span>{{ scope.row.createName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="60px" prop="createTime">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" :show-overflow-tooltip="true" sortable="name" align="left"
                         min-width="60px" prop="updateTime">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.operation')" align="center" column-key="operation"
                         class-name="small-padding fixed-width" fixed="right" width="250px">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-receiving"
              @click="handleClone(row)"
            >克隆</el-button>
            <i @click="handleEdit(row)" class="el-icon-edit table-operation" style="color: #2db7f5;"
               v-has-permission="['authority:application:edit']"></i>
            <i @click="handleDelete(row)" class="el-icon-delete table-operation" style="color: #f50;"
               v-has-permission="['authority:application:delete']"></i>
          </template>
        </el-table-column>

      </el-table>


      <pagination
        :limit.sync="queryParams.size"
        :page.sync="queryParams.current" :total="Number(tableData.total)"
        @pagination="fetch" v-show="tableData.total>0"/>

      <el-dialog :title="dialogFormVisibleName===1?'新建模版':'编辑模版'" :visible.sync="open" :fullscreen="true" style="margin-top: 0">
        <div class="tpl-create-content">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="ruleForm.remarks" type="textarea" />
            </el-form-item>
            <el-form-item label="模版" prop="formStructure">
              <div style="border-radius: 4px; border: 1px solid #ccc; overflow:hidden">
                <fm-making-form
                  ref="makingform"
                  style="height: 600px;"
                  preview
                  clearable
                  upload
                  generate-code
                  generate-json
                  :advance-fields="['editor', 'imgupload', 'file', 'subform', 'cascader']"
                >
                  <template slot="action" />
                </fm-making-form>
              </div>
            </el-form-item>
          </el-form>
          <div style="text-align: center">
            <el-button type="primary" @click="dialogFormVisibleName===1?submitForm('ruleForm'):editForm('ruleForm')">提交</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import Vue from 'vue'

import templateApi from '@/api/process/admin/template'
// 表单设计
import VueFormMaking from '@/components/VueFormMaking'
import '@/components/VueFormMaking/styles/FormMaking.css'

import ace from 'ace-builds'
import 'ace-builds/webpack-resolver'
// Vue.use(ace)
// Vue.use(GenerateForm)
// Vue.use(MakingForm)
import FmMakingForm from '@/components/VueFormMaking/components/Container'
import elDragDialog from '@/directive/el-drag-dialog'
import Pagination from '@/components/Pagination'
import {downloadFile, initQueryParams} from '@/utils/commons'
export default {
  name: 'Template',
  directives: {elDragDialog},
  components: {Pagination,FmMakingForm,VueFormMaking,ace},
  data() {
    return {
      dialogFormVisibleName: 1,
      queryParams: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      tplList: [],
      listQuery: {
        page: 1,
        per_page: 10
      },
      queryParams: initQueryParams({
        model: {}
      }),
      selection: [],
      tableKey: 0,
      tableData: {
        total: 0
      },
      ruleForm: {
        id: undefined,
        name: '',
        remarks: '',
        formStructure: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入模版名称', trigger: 'blur' }
        ],
        formStructure: [
          { required: true, message: '请设计模版', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询模版列表 */
    getList() {
      this.loading = true
      this.fetch();
    },
    handleCreate() {
      this.ruleForm = {
        id: undefined,
        name: '',
        remarks: '',
        formStructure: ''
      }
      this.dialogFormVisibleName = 1
      this.open = true
      this.$nextTick(() => {
        this.$refs.makingform.handleClear()
      })
    },
    handleEdit(row) {
      this.dialogFormVisibleName = 2
      templateApi.templateDetails({
        id: row.id
      }).then(response => {
        console.log("tpl模板数据", response);
        this.ruleForm = {
          id: response.data.data.id,
          name: response.data.data.name,
          remarks: response.data.data.remarks,
          formStructure: response.data.data.formStructure
        }
        this.open = true
        this.$nextTick(() => {
          this.$refs.makingform.setJSON(response.data.data.formStructure)
        })
      })
    },
    submitForm(formName) {
      this.handleSave(this.$refs.makingform.getJSON())
      this.$refs[formName].validate((valid) => {
        if (valid) {
          templateApi.createTemplate(this.ruleForm).then(() => {
            this.getList()
            this.open = false
          })
        }
      })
    },
    editForm(formName) {
      this.handleSave(this.$refs.makingform.getJSON())
      this.$refs[formName].validate((valid) => {
        if (valid) {
          templateApi.editTemplate(this.ruleForm).then(() => {
            this.getList()
            this.open = false
          })
        }
      })
    },
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        templateApi.deleteTemplate({
          id: row.id
        }).then(response => {
          if (response !== undefined) {
            this.getList()
            this.$message({
              type: 'success',
              message: '模版已删除!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSelectionChange() {},
    handleSave(values) {
      if (values.list.length > 0) {
        this.ruleForm.formStructure = values
      } else {
        this.ruleForm.formStructure = ''
      }
    },
    handleClone(row) {
      this.$confirm(`确认克隆模版 < ${row.name} > ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        templateApi.cloneTemplate(row.id).then(response => {
          console.log("response", response);
          this.getList()
          this.$message({
            type: 'success',
            message: '模版已克隆!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    fetch(params = {}) {
      this.loading = true;
      if (this.queryParams.timeRange) {
        this.queryParams.extra.createTime_st = this.queryParams.timeRange[0];
        this.queryParams.extra.createTime_ed = this.queryParams.timeRange[1];
      }
      this.queryParams.current = params.current ? params.current : this.queryParams.current;
      this.queryParams.size = params.size ? params.size : this.queryParams.size;
      templateApi.templateList(this.queryParams).then(response => {
        const res = response.data;
        if (res.isSuccess) {
          this.tableData = res.data;
        }
        this.loading = false
      }).finally(() => this.loading = false);
    },
    search() {
      this.fetch({
        ...this.queryParams,
      })
    },
    reset() {
      this.queryParams = initQueryParams({
        model: {}
      });
      this.$refs.table.clearSort()
      this.$refs.table.clearFilter()
      this.search()
    },
    sortChange(val) {
      this.queryParams.sort = val.prop;
      this.queryParams.order = val.order;
      if (this.queryParams.sort) {
        this.search();
      }
    },
    filterChange(filters) {
      for (const key in filters) {
        if (key.includes('.')) {
          const val = {};
          val[key.split('.')[1]] = filters[key][0];
          this.queryParams.model[key.split('.')[0]] = val;
        } else {
          this.queryParams.model[key] = filters[key][0]
        }
      }
      this.search()
    },
    onSelectChange(selection) {
      this.selection = selection
    },
    cellClick(row, column) {
      if (column['columnKey'] === "operation") {
        return;
      }
      if (column['columnKey'] === "clientId") {
        copy(row[column.property]);
        this.$message({
          message: this.$t('tips.copySelected'),
          type: 'success'
        })
        return;
      }

      let flag = false;
      this.selection.forEach((item) => {
        if (item.id === row.id) {
          flag = true;
          this.$refs.table.toggleRowSelection(row);
        }
      })
      if (!flag) {
        this.$refs.table.toggleRowSelection(row, true);
      }
    },
  }
}
</script>
